class Serve:
    def __init__(self, filename):
        self.lines = []
        with open(filename, "r", encoding = "utf8") as f:
            for line in f:
                self.lines.append(line)

    def __find_problem_range(self, id):
        for l in range(len(self.lines) - 1):
            if (self.lines[l].strip() == "[problem]" and
                    self.lines[l + 1].strip() == ("id = %s" % id)):
                r = l + 1
                while r < len(self.lines) and not self.lines[r].startswith("["):
                    r += 1

                return l, r

        return len(self.lines), len(self.lines)

    def __int_id(self, id):
        return ord(id) - ord('A') + 1

    def __create_new_problem(self, prob):
        res = ["[problem]\n"]
        res.append("%s = %s\n" % ("id", self.__int_id(prob["id"])))
        for k, v in prob.items():
            if k != "id":
                res.append(k + " = " + v + "\n")
        res.append("\n")
        return res

    def update_problem(self, prob):
        l, r = self.__find_problem_range(self.__int_id(prob["id"]))
        self.lines[l:r] = self.__create_new_problem(prob)

    def store(self, file):
        with open(file, "w", encoding='utf-8') as f:
            f.writelines(self.lines)
